<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push({ path: '/import' })"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!hasPermission('employee-add')"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column>
            <template v-slot:default="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 100%; object-fit: cover"
                @click="showQRDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot:default="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
            prop="enableState"
            :formatter="formatEnableState"
          >
            <template v-slot:default="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot:default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="sizes,prev, pager, next,total"
            :total="total"
            :page-size="page.size"
            :page-sizes="[5, 10, 20, 30]"
            @current-change="changePage"
            @size-change="changeSize"
          />
        </el-row>
      </el-card>
      <AddDemployee :show-dialog.sync="showDialog" />
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-dialog
        title="头像二维码"
        :visible="showQRCodeDialog"
        @close="showQRCodeDialog = false"
      >
        <el-row type="flex" justify="center" align="center">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getEmployeeList, delEmployee } from '@/api/employees'
import AddDemployee from './components/add-employee'
import { formatDate } from '@/filters'
// 利用枚举数据进行格式化数据
import EmployeeEnum from '@/api/constant/employees'
import AssignRole from './components/assign-role'
export default {
  components: {
    AddDemployee,
    AssignRole
  },
  data() {
    return {
      showRoleDialog: false,
      showQRCodeDialog: false,
      showDialog: false,
      userId: '',
      list: [],
      total: 0,
      page: {
        page: 1,
        size: 5
      }
    }
  },
  async created() {
    this.getEmployeeList()
  },
  methods: {
    // 将判断是否有权力点击按钮的逻辑放如混入 Mixin 中
    // hasPermission(points) {
    //   return this.$store.state.user.userInfo.roles.points.indexOf(points) > -1
    // },
    async editRole(id) {
      // 先获取默认有的角色
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
      this.userId = id
      // console.log(id)
    },
    showQRDialog(imgUrl) {
      if (imgUrl) {
        this.showQRCodeDialog = true
      }
      // 弹框打开前拿不到canvas的dom因此这里采用定时器或者 nextTick
      this.$nextTick(() => QRCode.toCanvas(this.$refs.mycanvas, imgUrl))
    },
    async exportExcel() {
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      const headerDirct = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // console.log(rows)
      const newArr = this.formatJson(headerDirct, rows)
      // console.log(newArr)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: Object.keys(headerDirct), // 表头 必填
          data: newArr, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 将数据转为二维数组，excel导出时配置的data是一个二维数组
    formatJson(headers, rows) {
      return rows.map((item) => {
        return Object.keys(headers).map((key) => {
          if (
            headers[key] === 'timeOfEntry' ||
            headers[key] === 'correctionTime'
          ) {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            console.log(11)
            const en = EmployeeEnum.hireType.find(
              (obj) => obj.id === item[headers[key]]
            )
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    delEmployee(id) {
      try {
        this.$confirm('确定删除该员工吗？')
          .then(async() => {
            await delEmployee(id)
            this.$message.success('删除员工成功')
            this.getEmployeeList()
          })
          .catch(() => {
            this.$message.warning('取消删除！')
          })
      } catch (error) {
        console.log(error)
      }
    },
    // 利用枚举数据进行格式化数据
    formatEmployment(row, column, cellValue, index) {
      const res = EmployeeEnum.hireType.find((item) => {
        return item.id === cellValue
      })
      return res ? res.value : '未知'
    },
    formatEnableState(row, column, cellValue, index) {
      const res = EmployeeEnum.workingState.find((item) => {
        return Number(item.id) === cellValue
      })
      return res ? res.value : '未知'
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.total = total
      this.list = rows
      // console.log(this.list)
    },
    changePage(newPage) {
      // console.log(newPage)
      this.page.page = newPage
      this.getEmployeeList()
    },
    changeSize(newSize) {
      // console.log(newSize)
      this.page.size = newSize
      this.getEmployeeList()
    }
  }
}
</script>

<style>
</style>
